from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin, ListModelMixin
from admin.utils.page import Mypage
from system.serializer.roles import RoleSerializer, RoleAllSerializer, CreateRoleSerializer, UpdateRoleSerializer, \
    UpdateRoleMenuSerializer
from system.models import Roles
from rest_framework.filters import SearchFilter


class RoleLevelView(APIView):
    """
    获取用户角色级别
    """

    def get(self, request):
        user = request.user
        role = user.roles.all()[0]
        return Response({
            'level': role.level
        })


class RoleView(ModelViewSet):
    queryset = Roles.objects.filter(is_delete=False)
    serializer_class = RoleSerializer
    filter_backends = [SearchFilter, ]
    search_fields = ('name', 'description')
    pagination_class = Mypage

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(serializer.data)


    def destroy(self, request, *args, **kwargs):
        instance = self.get_del_object(request)
        for i in instance:
            self.perform_destroy(i)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.update(is_delete=True)

    def get_del_object(self, request):  # 单个删除或批量删除
        id_list = request.data
        role_list = []
        for id in id_list:
            role_list.append(Roles.objects.filter(pk=id))
        return role_list

    def get_object(self, request):
        pk = request.data.get('id')
        return Roles.objects.filter(pk=pk).first()

    def get_serializer_class(self):
        if self.action == 'list':
            return RoleAllSerializer
        if self.action == 'create':
            return CreateRoleSerializer
        if self.action == 'update':
            return UpdateRoleSerializer


class UpdateRoleMenuView(GenericAPIView, UpdateModelMixin):
    queryset = Roles.objects.filter(is_delete=False)
    serializer_class = UpdateRoleMenuSerializer

    def put(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response()

    def get_object(self, request):
        request_id = request.data.get('id')  # 当前请求的角色id
        return Roles.objects.filter(pk=request_id).first()


class GetAllRolesView(GenericAPIView, ListModelMixin):
    queryset = Roles.objects.filter(is_delete=False)
    serializer_class = RoleSerializer
    pagination_class = Mypage
    def get(self, request, *args, **kwargs):
        """
        获取所有的角色信息
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)






class RetrieveView(GenericAPIView, ListModelMixin):
    """
    返回单条信息
    """
    serializer_class = RoleAllSerializer
    queryset = Roles.objects.filter(is_delete=False).first()

    def get(self, request, pk, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = Roles.objects.filter(is_delete=False, pk=pk)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
